import srorageKey from './srorage/key';
import { getLocal, setLocal } from './srorage';
import { WECHAT_TEMPLACTE_ID } from '@/config/base';

/**
 * 获取元素信息
 * @param {*} domeClass
 * @param {*} isAll
 * @returns
 */
export const getDomeInfo = function (domeClass, isAll = true) {
	return new Promise((resolve, reject) => {
		uni.createSelectorQuery()
			.in(this)
			[isAll ? 'selectAll' : 'select'](domeClass)
			.boundingClientRect((res) => {
				resolve(res);
			})
			.exec();
	});
};

/**
 * 判断用户是否微信授权 & 手机号授权 & 渠道信息填写
 */
export const isMultipleAuthor = function () {
	const userInfo = getLocal(srorageKey.userInfo) || {};
	// const { userId, channelCount } = getLocal(srorageKey.userInfo) || {};
	const token = getLocal(srorageKey.AuthorizedToken);

	const url = '/authorizePage/';
	if (!token || !Object.keys(userInfo).length) {
		uni.navigateTo({
			url: `${url}WechatAuthorize`
		});
		return false;
	}

	if (!userInfo.userId) {
		uni.navigateTo({
			url: `${url}PhoneAuthorize`
		});
		return false;
	}

	/**
	 * 申请探店时，检测用户有没有渠道信息填写
	 */
	/* eslint-disable */
	const pages = getCurrentPages();
	const beforePage = pages[pages.length - 1];

	if (beforePage.route !== 'tandianPage/ProductDetail') {
		return true;
	}
	/* eslint enable */

	// if (!userInfo.channelCount) {
	// 	uni.navigateTo({
	// 		url: `/thirdManage/dyAccount`
	// 	});
	// 	return false;
	// }

	return true;
};

/**
 * 判断 session_key 是否过期
 * @returns
 */
export const getSessionKeyExpired = function () {
	return new Promise((resolve) => {
		uni.checkSession({
			success: () => {
				resolve(true);
			},

			fail: () => {
				resolve(false);
			}
		});
	});
};

/**
 *
 * 统一分享小程序功能
 * @return
 */
export const onShareApp = {
	onShareAppMessage: () => {
		/* eslint-disable */
		const routes = getCurrentPages();
		const { route } = routes[routes.length - 1] || {};

		return {
			path: route,
			title: '联联探客申请探店赚佣金'
			// imageUrl: `${defaultImageUrl}image/img_share.png`
		};
		/* eslint enable */
	}
};

/**
 * 判断订阅通知是否点击了 总是保持以上选择
 */
export const isSubscribeNotifications = function () {
	return new Promise((resolve, reject) => {
		wx.getSetting({
			withSubscriptions: true,
			success: (res) => {
				const { subscriptionsSetting } = res;

				if (subscriptionsSetting[WECHAT_TEMPLACTE_ID]) {
					return resolve(true);
				}

				if ((subscriptionsSetting.itemSettings || {})[WECHAT_TEMPLACTE_ID]) {
					return resolve(true);
				}

				return resolve(false);
			}
		});
	});
};

/**
 * 获取时分秒
 */
export const liveShowDateFormat = (time) => {
	if (time <= 0 || !time) {
		return '00:00:00';
	}

	let hour = Math.floor(time / 1000 / 3600);
	let min = Math.floor((time / 1000 - hour * 3600) / 60);
	let sec = Math.floor(time / 1000 - hour * 3600 - min * 60);
	hour = hour >= 10 ? hour : '0' + hour;
	min = min >= 10 ? min : '0' + min;
	sec = sec >= 10 ? sec : '0' + sec;
	return hour + ':' + min + ':' + sec;
};

/**
 * 验证身份证号码
 * @param { String } code 身份证号码
 */
export const identityIDCard = (code) => {
	// 身份证号前两位代表区域
	const city = {
		11: '北京',
		12: '天津',
		13: '河北',
		14: '山西',
		15: '内蒙古',
		21: '辽宁',
		22: '吉林',
		23: '黑龙江 ',
		31: '上海',
		32: '江苏',
		33: '浙江',
		34: '安徽',
		35: '福建',
		36: '江西',
		37: '山东',
		41: '河南',
		42: '湖北 ',
		43: '湖南',
		44: '广东',
		45: '广西',
		46: '海南',
		50: '重庆',
		51: '四川',
		52: '贵州',
		53: '云南',
		54: '西藏 ',
		61: '陕西',
		62: '甘肃',
		63: '青海',
		64: '宁夏',
		65: '新疆',
		71: '台湾',
		81: '香港',
		82: '澳门',
		91: '国外 '
	};

	// 身份证格式正则表达式
	const idCardReg = /^[1-9]\d{5}(19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;

	let errorMessage = ''; // 错误提示信息
	let isPass = true; // 身份证验证是否通过（true通过、false未通过）

	// 如果身份证不满足格式正则表达式
	if (!code) {
		errorMessage = '请输入身份证号码';
		isPass = false;
	} else if (!code.match(idCardReg)) {
		errorMessage = '请输入正确的身份证号码';
		isPass = false;
	} else if (!city[code.substr(0, 2)]) {
		// 区域数组中不包含需验证的身份证前两位
		errorMessage = '请输入正确的身份证号码';
		isPass = false;
	} else if (code.length === 18) {
		// 18位身份证需要验证最后一位校验位
		code = code.split('');
		const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];

		// 校验位
		const parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];

		let sum = 0;
		let ai = 0;
		let wi = 0;

		for (let i = 0; i < 17; i++) {
			ai = parseInt(code[i]);
			wi = factor[i];
			sum += ai * wi; // 开始计算并相加
		}

		const last = parity[sum % 11]; // 求余

		if (last.toString() !== code[17]) {
			errorMessage = '请输入正确的身份证号码';
			isPass = false;
		}
	}

	return {
		errorMessage,
		isPass
	};
};

/**
 * 验证姓名 & 持卡人姓名
 * @param { String } name 姓名
 */
export const checkName = (name) => {
	const checkReg = /^[\u4e00-\u9fa5]{2,5}$/;

	let isPass = true;
	let errorMessage = ''; // 错误提示信息

	if (!checkReg.test(name)) {
		isPass = false;
		errorMessage = '请输入正确的姓名';
	}

	return {
		isPass,
		errorMessage
	};
};

/**
 *
 * @param {*} bankno  银行卡
 * @returns luhn校验规则：16位银行卡号（19位通用）: 银行卡号Luhn校验算法
 * 1.将未带校验位的 15（或18）位卡号从右依次编号 1 到 15（18），位于奇数位号上的数字乘以 2。
 * 2.将奇位乘积的个十位全部相加，再加上所有偶数位上的数字。
 * 3.将加法和加上校验位能被 10 整除。
 */
export const testPaycard = function (bankno) {
	// if (!bankno || !/(^\d{16}$)|(^\d{19}$)/.test(bankno)) {
	// 	return {
	// 		isPass: false,
	// 		errorMessage: '请输入正确的银行卡号'
	// 	};
	// }

	if (![15, 16, 17, 18, 19].includes(bankno.length)) {
		return {
			isPass: false,
			errorMessage: '请输入正确的银行卡号'
		};
	}

	return {
		isPass: true,
		errorMessage: '请输入正确的银行卡号'
	};

	// if (!payCard || !/(^\d{16}$)|(^\d{19}$)/.test(payCard)) {
	//     return {
	// 		isPass: false,
	// 		errorMessage: '请输入正确的银行卡号'
	// 	}
	// }
	// const everyNum = String(payCard).split(''); // 将银行卡的所有数字拆分

	// everyNum.forEach((num, index) => {
	//     if (index % 2 === 0) { // 从右往左  偶数位
	//         num = Number(num).toString(2) + '0'; // 转换为二进制，并将二进制左移一位
	//         num = parseInt(num, 2); // 转回十进制
	//         num = (num / 10 | 0) + num % 10; // 当前数字每位的和
	//         everyNum[index] = num;
	//     }
	// });

	// // 统计总和 % 10是否整除
	// return {
	// 	errorMessage: '请输入正确的银行卡号',
	// 	isPass: everyNum.reduce((tol, num) => tol + parseInt(num), 0) % 10 === 0,
	// }
};

/**
 * 格式化佣金模式
 * @param {*} target 目标
 * @param {*} formatMoney 是否处理金额
 * @returns
 */
export const formatCommissionsModel = function (target, formatMoney = false) {
	/**
	 * 1 拍摄费
	 * 2 拍摄费 加CPS
	 * 3 CPS
	 */
	return (target || []).map((item) => {
		const { commissionType, commissionMoney } = item;

		const value = formatMoney ? commissionMoney / 100 || 0 : commissionMoney;

		let label = '';
		[1, 2].includes(commissionType) && (label = '拍摄费');
		commissionType === 2 && (label += `+${value}元/单`);
		commissionType === 3 && (label = `${value}元/单`);

		return {
			label,
			value,
			commissionType
		};
	});
};

/**
 * 格式化单个佣金模式
 * @param {*} target 目标
 * @param {*} formatMoney 是否处理金额
 * @returns
 */
export const formatSingleCommissions = function (commissionType) {
	/**
	 * 1 拍摄费
	 * 2 拍摄费 加CPS（佣金）
	 * 3 CPS（佣金）
	 */
	let label = '';
	[1, 2].includes(commissionType) && (label = '拍摄费');
	commissionType === 2 && (label += '+佣金');
	commissionType === 3 && (label = '佣金');

	return label;
};

/**
 * 格式视频播放时长
 * @param {*} value
 * @returns
 */
export const secondFormatMinute = (value) => {
	let minute = Math.floor(value / 60);
	let second = Math.floor(value % 60);

	minute < 10 && (minute = `0${minute}`);
	second < 10 && (second = `0${second}`);

	return `${minute}:${second}`;
};

export const requestPayment = (params) => {
	const { timeStamp, nonceStr, packageValue, signType, paySign } = params;

	return new Promise((resolve) => {
		uni.requestPayment({
			paySign,
			signType,
			nonceStr,
			timeStamp,
			package: packageValue,

			success: () => {
				resolve(true);
			},

			fail: () => {
				resolve(false);
			}
		});
	});
};

export const InvitationCodeMistakeHintList = [
	{
		type: -1,
		hint: '邀请码不存在'
	},
	{
		type: 2,
		hint: '邀请码已失效'
	},
	{
		type: 3,
		hint: '请勿重复使用邀请码'
	},
	{
		type: 4,
		hint: '邀请码已达使用上限'
	}
];

/**
 * 获取素材文件大小
 * @returns
 */
export const getMaterialFileSize = (params = {}) => {
	const { padding = 40, height = 160, margin = 20 } = params;

	const { screenWidth, windowWidth } = uni.getSystemInfoSync();
	const staticBoxWidth = (screenWidth || windowWidth) - uni.upx2px(padding);

	let itemSize = 0;

	let widthHeight = uni.upx2px(height);
	let defaultMargin = uni.upx2px(margin);
	let multiple = (defaultMargin / widthHeight).toFixed(2);

	const diff = (staticBoxWidth / widthHeight).toFixed(2);

	itemSize = Math.floor(diff);
	let marginLeft = (diff - (itemSize - 1)) * defaultMargin;

	if (marginLeft > defaultMargin) {
		const marginDiff = defaultMargin * multiple;

		marginLeft = defaultMargin - marginDiff;
		widthHeight = marginDiff + widthHeight + multiple * defaultMargin;
	}

	return {
		itemSize,
		marginLeft,
		widthHeight
	};
};

// 上传 & 下载提示
export const hintUploadAndDownload = (isUplaod = true) => {
	return new Promise((resolve) => {
		const text = isUplaod ? '上传' : '下载';

		const confirmText = `继续${text}`;
		const content = `退出后将导致数据中断，是否退出${text}？`;

		uni.showModal({
			content,
			title: '提示',

			cancelText: '残忍离开',
			cancelColor: '#576B95',

			confirmText,
			confirmColor: '#333',

			success: resolve
		});
	});
};

let systemInfo = uni.getSystemInfoSync() || {};
export function saveCodeImageCom(params='',callBack){
	// const self = this;
	console.log(params);
	
	if (!params) {
		uni.showToast({
			title: '二维码无效',
			icon: 'none'
		});
		return;
	}
	uni.showLoading({
		title: '处理中…'
	});
	wx.getImageInfo({
		src: params, 
		success: function (urlObj = {}) {
		  console.log(urlObj);
		  const {path = ''} = urlObj
		  uni.saveImageToPhotosAlbum({
			filePath: path,
			success: function (res = {}) {
				console.log(res)
				console.log('save success');
				// self.isPopupBind = false;
				uni.hideLoading();
				if (systemInfo.platform === 'ios') {
					uni.showToast({
						title: '保存成功'
					});
				}
				
				callBack()
			},
			fail(err = {}){
				const { errMsg = '' }=err
				uni.hideLoading();
				if(errMsg === 'saveImageToPhotosAlbum:fail cancel'){
					uni.showToast({
						title: '您已取消保存',
						icon:'none'
					});
				}else{
					uni.showToast({
						title: '保存失败',
						icon:'none'
					});
				}
				console.log(err)
			}
		});
		},
		fail(err){
			console.log(err)
			uni.hideLoading();
			uni.showToast({
				title: '二维码下载失败',
				icon:'none'
			});
		}
	})
	
}

export function judgeOneTime() {
	const getPreTime = getLocal(srorageKey.newUserOneTime) || [];
	let nowDate = setOneTime() || [];
	
	if (nowDate[0] === getPreTime[0]) {
		if (nowDate[1] === getPreTime[1]) {
			if (nowDate[2] === getPreTime[2]) {
				return false;
			} else {
				return true;
			}
		} else {
			return true;
		}
	} else {
		return true;
	}
}
export function setOneTime(isSet = false) {
	let nowDate = new Date();
	let nowYear = nowDate.getFullYear();
	let nowMonth = nowDate.getMonth() + 1;
	let nowDay = nowDate.getDate() ? Number(nowDate.getDate()) : 1;
	// console.log(nowDate, nowYear, nowMonth, nowDay);
	if (isSet) {
		setLocal(srorageKey.newUserOneTime, [nowYear, nowMonth, nowDay]);
	} else {
		return [nowYear, nowMonth, nowDay];
	}
}